package com.leo.script;

import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.AviatorEvaluatorInstance;
import com.googlecode.aviator.script.AviatorScriptEngine;
import lombok.SneakyThrows;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.SimpleBindings;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

public class AviatorUtils {

    public static void main(String[] args) {
        custom();
        engine();
    }

    @SneakyThrows
    public static void custom() {
        Object result = AviatorEvaluator.compile("a + b").execute(Map.of("a", new BigDecimal("0.1"), "b", new BigDecimal("0.2")));
        System.out.println(result);

        result = AviatorEvaluator.compile("reduce(list, +, 0)").execute(Map.of("list", List.of(new BigDecimal("0.1"), new BigDecimal("0.2"))));
        System.out.println(result);

        AviatorEvaluator.defineFunction("sum", "lambda (l) -> reduce(l, +, 0) end");
        result = AviatorEvaluator.compile("sum(list)").execute(Map.of("list", List.of(new BigDecimal("0.1"), new BigDecimal("0.2"))));
        System.out.println(result);
    }

    @SneakyThrows
    public static void engine() {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("aviator");
        Object result = engine.eval("a + b", new SimpleBindings(Map.of("a", new BigDecimal("0.1"), "b", new BigDecimal("0.2"))));
        System.out.println(result);

        AviatorEvaluatorInstance instance = ((AviatorScriptEngine) engine).getEngine();
        instance.defineFunction("sum", "lambda (l) -> reduce(l, +, 0) end");

        result = engine.eval("sum(list)", new SimpleBindings(Map.of("list", List.of(new BigDecimal("0.1"), new BigDecimal("0.2")))));
        System.out.println(result);
    }
}
